package com.ahjz.ahjzdemo.tcp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class TcpClient {
	private Socket socket = null;
	private BufferedReader reader = null;
	private BufferedWriter writer = null;

	public TcpClientCallback callback = null;

	private boolean isExit = false;

	public boolean init(String ipString, int port) {
		try {
			socket = new Socket(ipString, port);
			reader = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			writer = new BufferedWriter(new OutputStreamWriter(
					socket.getOutputStream()));

			startReceiveData();
			return true;
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	public void stop() {
		isExit = true;

		try {
			if (reader != null) {
				reader.close();
			}

			if (writer != null) {
				writer.close();
			}

			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void startReceiveData() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					while (!isExit) {
						String msg = reader.readLine();
						if (msg != null && callback != null) {
							callback.onReceiveMessage(msg);
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	public void writeData(String msg) {
		if (writer != null) {
			try {
				writer.write(msg);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public interface TcpClientCallback {
		public void onReceiveMessage(String msg);
	}
}